2.webview_flutter 加载监听

NavigationDelegate 中包含一系列回调:

  1. onNavigationRequest:是否拦截请求
  2. onPageStarted:页面跳转开始
  3. onPageFinished:页面跳转结束
  4. onProgress:网页加载进度
  5. onWebResourceError:网络资源错误
  6. onUrlChange:url 发生变化
  7. onHttpAuthRequest 网页权限请求
  8. onHttpError:请求错误

监听网页加载进度

controller
  ..setNavigationDelegate(
    NavigationDelegate(
      onProgress: (int progress) {
        debugPrint('WebView is loading (progress : $progress%)');
      },
      onPageStarted: (String url) {
        debugPrint('Page started loading: $url');
      },
      onPageFinished: (String url) {
        debugPrint('Page finished loading: $url');
      },
      onUrlChange: (UrlChange change) {
        debugPrint('url change to ${change.url}');
      },

监听资源加载错误

controller
  ..setNavigationDelegate(
    NavigationDelegate(
      onWebResourceError: (WebResourceError error) {
        debugPrint('''
Page resource error:
code: ${error.errorCode}
description: ${error.description}
errorType: ${error.errorType}
isForMainFrame: ${error.isForMainFrame}
      ''');
      },
      onHttpError: (HttpResponseError error) {
        debugPrint('Error occurred on page: ${error.response?.statusCode}');
      },
    ),
  )

网页请求拦截

controller
  ..setNavigationDelegate(
    NavigationDelegate(
      onNavigationRequest: (NavigationRequest request) {
        if (!request.url.startsWith('http')) {
          debugPrint('blocking navigation to ${request.url}');
          return NavigationDecision.prevent;
        }
        if (request.url.startsWith('https://www.youtube.com/')) {
          debugPrint('blocking navigation to ${request.url}');
          return NavigationDecision.prevent;
        }
        debugPrint('allowing navigation to ${request.url}');
        return NavigationDecision.navigate;
      },
    ),
  )

本文作者:Maeiee

本文链接:2.webview_flutter 加载监听

版权声明:如无特别声明,本文即为原创文章,版权归 Maeiee 所有,未经允许不得转载!


喜欢我文章的朋友请随缘打赏,鼓励我创作更多更好的作品!